package com.abigdreamer.im.server.cmd.resouse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.thoughtworks.xstream.XStream;

public class ConfigFactory {

	private static ConfigFactory instance;
	private CMDConfig config;
	
	public static ConfigFactory getInstance() {
		if(null==instance){
			instance=new ConfigFactory();
		}
		return instance;
	}

	private ConfigFactory(){
	}
	
	public CMDConfig getCMDConfig(){
		if(null==config){
		    config=new CMDConfig();
			File file=getFile(CMDConfig.class.getPackage(),"cmd_config.xml");
			XStream xstream=getConfigXStream();
			try {
				FileInputStream xml=new FileInputStream(file);
				config=(CMDConfig)xstream.fromXML(xml);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		return config;
	}
	
	
	public static XStream getConfigXStream(){
		XStream xstream = new XStream();
		xstream.alias("Command-Configuration", CMDConfig.class);
		xstream.alias("command", CommandBean.class);
		xstream.alias("map", Mapping.class);
		
		xstream.useAttributeFor(Mapping.class, "id");
		xstream.useAttributeFor(Mapping.class, "beanName");
		xstream.useAttributeFor(CommandBean.class, "name");
		xstream.useAttributeFor(CommandBean.class, "classPath");
		return xstream;
	}
	public static File getFile(Package dirPackage, String fileName) {
		String path =Thread.currentThread().getContextClassLoader().getResource("").getPath();
		File file = new File(path+"/com/csu/server/cmd/resouse/cmd_config.xml");
		System.out.println("path:"+path);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}
	
    public static void main(String[] args){
        try{
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();    //添加
        File af=new File(path+"/com/csu/cmd/resouse/cmd_config.xml");
        if(!af.exists()) {
        	System.out.println("nullEXIST");
        }else{
        	XStream xstream=getConfigXStream();
			try {
				FileInputStream xml=new FileInputStream(af);
				CMDConfig config=(CMDConfig)xstream.fromXML(xml);
				System.out.println(config);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
        }
        }
        catch(Exception e){
            System.out.println("HugeERROR");
        }
    }
        
}
